package com.binvshe.binvshe.opus;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.ui.LoginActivity;
import com.binvshe.binvshe.account.utils.FragmentUtils;
import com.binvshe.binvshe.app.home.ClassEvent;
import com.binvshe.binvshe.app.home.CommentFragment;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.entity.HomeEntity;
import com.binvshe.binvshe.mine.view.CommentDialog;
import com.cncn.youmengsharelib.ShareData;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.share.BaseShareFragment;
import com.pachong.android.framework.share.SharePlatformsFragment;
import com.pachong.android.frameworkbase.customviews.BadgeView;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.R.attr.data;
import static android.R.attr.id;
import static com.binvshe.binvshe.account.AccountManager.getTokenInfo;
import static com.binvshe.binvshe.app.home.adapter.MediaType.IMAGE;
import static com.binvshe.binvshe.app.home.adapter.MediaType.LONG_STORY;
import static com.binvshe.binvshe.app.home.adapter.MediaType.SHORT_STORY;
import static com.binvshe.binvshe.app.home.adapter.MediaType.TEXT;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2017/1/16
 */

public class OpusDetailsNewAcitvity extends BaseActivity {
    private static final String KEY_ART_ID = "ART_ID";

    @Bind(R.id.frlytContent)
    FrameLayout mFrlytContent;
    @Bind(R.id.frlytComment)
    FrameLayout mFrlytComment;
    @Bind(R.id.ivLike)
    ImageView mIvLike;
    @InjectExtra(KEY_ART_ID)
    int mArtID;//内容id
    BadgeView mCommentNum;
    BadgeView mLikeNum;

    ShareData mShareData = null;
    @Bind(R.id.ivComment)
    ImageView mIvComment;
    @Bind(R.id.ivShare)
    ImageView mIvShare;
    private String mUserId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Dart.inject(this);
        ButterKnife.bind(this);
        mCommentNum = new BadgeView(this);
        mCommentNum.setTargetView(mIvComment);
        mLikeNum=new BadgeView(this);
        mLikeNum.setTargetView(mIvLike);
        enableBackButton();
        getOpusDetails();
        FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.frlytComment, CommentFragment.newInstance(mArtID, "article"));//评论部分
    }



    public static void start(Context context, int artID) {
        Intent starter = new Intent(context, OpusDetailsNewAcitvity.class);
        starter.putExtra(KEY_ART_ID, artID);
        context.startActivity(starter);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_opus_new, container, false);
    }


    /**
     * 数据与view绑定
     *
     * @param o
     */
    private void setDataView(HomeEntity o) {
        if (o == null) {
            return;
        }
        initShareContent(o);
          mUserId = o.getUser().getUserId();

        Log.e("id_userid", mUserId +"");
        mCommentNum.setBadgeCount(o.getComment_count());
        mLikeNum.setBadgeCount(o.getLike_count());
        if (o.isLike()) {
            setLike(true);
        } else {
            setLike(false);
        }

        switch (o.getMedia_type()) {
            case IMAGE://图片类型
                FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.frlytContent,
                        new ImageTypeFragment(o));//作品部分
                break;
            case TEXT://小说类型
            case LONG_STORY:
            case SHORT_STORY:
                FragmentUtils.replaceFragment(getSupportFragmentManager(), R.id.frlytContent,
                        new StoryTypeFragment(o));//作品部分
                break;
        }
    }


    private void setLike(boolean like) {
        final MyHttpRequest request = new MyHttpRequest(OpusDetailsNewAcitvity.this);
        final String url = String.format(UrlCenter.LIKE, "article", mArtID);
        if (like) {
            mIvLike.setImageDrawable(getResources().getDrawable(R.mipmap.icon_dianzarn_p));
            mIvLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    request.delete(url, null, new DataRequestListener<String>(String.class) {
                        @Override
                        public void onStart(Context context, String url) {
                            enableProgress(false);
                            super.onStart(context, url);
                        }

                        @Override
                        public void onSuccess(String o) {
                            super.onSuccess(o);
                            mLikeNum.setBadgeCount(mLikeNum.getBadgeCount()-1);
                            setLike(false);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                            LoginActivity.start(OpusDetailsNewAcitvity.this);
                            EasyToast.showToast(OpusDetailsNewAcitvity.this, strMsg);
                        }
                    });
                }
            });
        } else {
            mIvLike.setImageDrawable(getResources().getDrawable(R.mipmap.icon_likevvvv));
            mIvLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    UrlParams urlParams = new UrlParams();
                    request.post(url, urlParams, new DataRequestListener<String>(String.class) {
                        @Override
                        public void onStart(Context context, String url) {
                            enableProgress(false);
                            super.onStart(context, url);
                        }

                        @Override
                        public void onSuccess(String o) {
                            super.onSuccess(o);
                            setLike(true);
                            mLikeNum.setBadgeCount(mLikeNum.getBadgeCount()+1);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                            EasyToast.showToast(OpusDetailsNewAcitvity.this, strMsg);
                        }
                    });
                }
            });
        }
    }

    /**
     * 获取作品详情
     */
    public void getOpusDetails() {
        String url = String.format(UrlCenter.ARTICLE_DETAILS, mArtID);
        IHttpRequest request = new MyHttpRequest(this);
        request.get(url, null, new DataRequestListener<HomeEntity>(HomeEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(HomeEntity o) {
                super.onSuccess(o);
                setDataView(o);
                String mmUserrId = AccountManager.getTokenInfo().getUser_id()+"";
                if(mmUserrId.equals(mUserId)){
                    getCustomToolbar().addRightImageButton(R.drawable.icon_more_detel, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            List<String> list = new ArrayList<String>();
                            IOSAlertListFragment iosAlertListFragment = new IOSAlertListFragment();
                            AdapterView.OnItemClickListener onItemClickListener = null;
                            list.add("删除");
                            onItemClickListener =new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    switch (position){
                                        case 0:
                                            deleteArticle(mArtID);
                                            break;
                                    }
                                }
                            };
                            iosAlertListFragment.setActionList(onItemClickListener, list);
                            iosAlertListFragment.show(getSupportFragmentManager());
                        }
                    });
                }
            }
                /**
                 * 删除作品请求
                 */
                private void deleteArticle(int articleID) {
                    IHttpRequest request = new MyHttpRequest(OpusDetailsNewAcitvity.this);
                    String url = String.format(UrlCenter.DELETE_ARTICLE, articleID + "");
                    request.delete(url, new UrlParams(), new DataRequestListener(String.class) {
                        @Override
                        public void onStart(Context context, String url) {
                            super.onStart(context, url);
                        }
                        @Override
                        public void onSuccess(Object o) {
                            Toast.makeText(OpusDetailsNewAcitvity.this, ("删除成功"), Toast.LENGTH_SHORT).show();
                            finish();
                            super.onSuccess(o);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                        }
                    });
                }



            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }


    @OnClick({R.id.ivComment, R.id.ivShare})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivComment:
                showCommentDialog("article");
                break;
            case R.id.ivShare:
                if (mShareData != null) {
                    BaseShareFragment fragment = SharePlatformsFragment.showShareFragment(this, mShareData);
                    fragment.setShareListener(new ShareListener() {
                        @Override
                        public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailsNewAcitvity.this, "分享成功");
                        }

                        @Override
                        public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailsNewAcitvity.this, "分享失败");
                        }

                        @Override
                        public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                            EasyToast.showToast(OpusDetailsNewAcitvity.this, "分享取消");
                        }
                    });
                }
                break;
        }
    }

    /**
     * 弹出评论框
     *
     * @param type
     */
    private void showCommentDialog(final String type) {
        CommentDialog commentDialog = CommentDialog.newInstance("评论", "写评论", 4, true);
        commentDialog.show(getSupportFragmentManager(), "tag");
        commentDialog.setOnClickable(new CommentDialog.CommentClickable() {

            @Override
            public void btnEnter(String comment) {
                MyHttpRequest request = new MyHttpRequest(OpusDetailsNewAcitvity.this);
                String url = String.format(UrlCenter.COMMENT, type, mArtID);
                JSONObject jobj = new JSONObject();
                try {
                    jobj.put(ParamKey.CONTENT, comment);
                    request.post(url, jobj, new DataRequestListener<String>(String.class) {
                        @Override
                        public void onStart(Context context, String url) {
                            enableProgress(false);
                            super.onStart(context, url);
                        }
                        @Override
                        public void onSuccess(String str) {
                            super.onSuccess(str);
                            EventBus.getDefault().post(new ClassEvent.RefreshEvent());
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void initShareContent(HomeEntity o) {
        if (o != null) {
            String articleUrl = String.format("http://app.binvshe.com/static/app/index.html#/article/%1$s", o.getId());
            mShareData = new ShareData(o.getUser().getPortrait(), o.getTitle(), o.getContent(), articleUrl);
        }
    }
}
